package com.xiyu.service.repository.material.stock;

import com.xiyu.service.model.material.info.MaterialCategoryFetcher;
import com.xiyu.service.model.material.info.MaterialInfoFetcher;
import com.xiyu.service.model.material.stock.MaterialStockDetailFetcher;
import com.xiyu.service.vo.material.stock.StockPageQueryInput;
import com.xiyu.service.model.material.stock.MaterialStockDetail;
import com.xiyu.service.model.material.stock.MaterialStockDetailTable;
import org.babyfish.jimmer.spring.repository.JRepository;
import org.babyfish.jimmer.Page;
import org.springframework.util.StringUtils;

import java.util.Optional;

public interface MaterialStockDetailRepository extends JRepository<MaterialStockDetail, Long> {
    MaterialStockDetailTable materialStockDetailTable = MaterialStockDetailTable.$;

    default Optional<MaterialStockDetail> findByUniqueColumn(Long warehouseId, Long materialId,
                                                             String batchNo,
                                                             String productionDate, String expireDate){
        return sql().createQuery(materialStockDetailTable)
                .where(materialStockDetailTable.warehouseId().eq(warehouseId))
                .where(materialStockDetailTable.materialId().eq(materialId))
                .where(materialStockDetailTable.batchNo().eq(batchNo))
                .where(materialStockDetailTable.productionDate().eq(productionDate))
                .where(materialStockDetailTable.expireDate().eq(expireDate))
                .select(materialStockDetailTable)
                .fetchOptional();

    }

    default Page<MaterialStockDetail> pageQuery(StockPageQueryInput inputVO){
        return sql().createQuery(materialStockDetailTable)
                .whereIf(StringUtils.hasText(inputVO.getBatchNo()), () -> materialStockDetailTable.batchNo().like(inputVO.getBatchNo()))
                .whereIf(inputVO.getWarehouseId() != null, materialStockDetailTable.warehouseId().eq(inputVO.getWarehouseId()))
                .whereIf(StringUtils.hasText(inputVO.getMaterialName()), () -> materialStockDetailTable.material().materialName().like(inputVO.getMaterialName()))
                .orderBy(materialStockDetailTable.id().desc())
                .select(materialStockDetailTable.fetch(
                        MaterialStockDetailFetcher.$.allTableFields().material(
                                MaterialInfoFetcher.$.allTableFields().category(
                                        MaterialCategoryFetcher.$.allTableFields()
                                )
                        )
                ))
                .fetchPage(inputVO.getPageNo() - 1, inputVO.getPageSize());
    }

}